<template>
  <el-row id="device-manage-container">
    <el-row v-if="!isViewShow" class="permission">
      没有权限!
    </el-row>

    <el-card v-else class="box-card">
      <div slot="header" class="clearfix">
        <span>设备管理</span>
        <el-button :disabled="!isViewEdit" @click="handlerNewDevice" style="margin-left: 1720px;padding: 6px 8px;" type="primary">添加</el-button>
      </div>

      <el-row class="box-card-content">

        <!--条件栏-->
        <el-row>
          <el-input placeholder="请输入内容" v-model="selectConditionValue" class="input-with-select">
            <el-select @change="onSelectChange" v-model="selectValue" slot="prepend" placeholder="请选择">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
            <el-button @click="onSearch" slot="append" icon="el-icon-search"></el-button>
          </el-input>
        </el-row>

        <!--表格栏-->
        <el-row>
          <el-table
            :data="tableDatas"
            style="width: 100%"
            header-align="center"
            max-height="620">
            <el-table-column
              prop="deviceName"
              align="center"
              label="设备名">
            </el-table-column>
            <el-table-column
              prop="id"
              align="center"
              label="设备Id">
            </el-table-column>
            <el-table-column
              prop="operateStatus"
              align="center"
              label="运行状态">
            </el-table-column>
            <el-table-column
              prop="model"
              align="center"
              label="设备型号">
            </el-table-column>
            <el-table-column
              prop="specification"
              align="center"
              label="设备规格">
            </el-table-column>
            <el-table-column
              prop="lastStartTime"
              align="center"
              label="上次开机时间">
            </el-table-column>
            <el-table-column
              align="center"
              label="操作">
              <template slot-scope="scope">
                <el-button
                  :disabled="!isViewEdit"
                  @click.native.prevent="handlerOpenEditDialog(scope.$index, scope.row)"
                  type="primary"
                  size="small">
                  编辑
                </el-button>
                <el-button
                  :disabled="!isViewEdit"
                  @click.native.prevent="handlerOpenDialog(scope.$index, scope.row)"
                  type="primary"
                  size="small">
                  运行记录
                </el-button>
                <el-button
                  :disabled="!isViewEdit"
                  @click.native.prevent="handlerDelete(scope.$index, scope.row)"
                  type="primary"
                  size="small">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-row>

      </el-row>

      <!--分页-->
      <div style="text-align: center;margin-top: 10px;">
        <el-pagination
          background
          layout="prev, pager, next"
          :total="paginationCount"
          :current-page="currentPage"
          :page-size="pageSize"
          @current-change="onPageChange">
        </el-pagination>
      </div>
    </el-card>

    <!--运行记录弹窗-->
    <el-dialog :visible.sync="runLogDialogShow">
      <el-row slot="title">
        <span style="font-size: 18px">运行记录</span>
      </el-row>

      <el-row>
        <el-date-picker
          :type="pickerType"
          @change="onPickerChange"
          :value-format="dateFormat"
          v-model="currentDate"
          placeholder="选择日期时间">
        </el-date-picker>
      </el-row>

      <el-row>
        <BaseEchartsComponent ref="dmcRunLogLineChart" :id="'dmc_runloglinechart'" :data="lineChartsOptions" :time="chartTime"/>
      </el-row>

    </el-dialog>

    <!--设备添加弹窗-->
    <el-dialog :visible.sync="addDialogShow">
      <el-row slot="title">
        <span style="font-size: 18px">新增/编辑</span>
        <el-button @click="postNewDevice('addForm')" style="margin-left: 760px; padding: 6px 10px" type="primary" :loading="false">提交</el-button>
      </el-row>
      <el-row class="add-dialog-content">
        <el-form ref="addForm" :model="addForm" :rules="addRule" >
          <el-row>
            <el-col :span="8">
              <el-form-item label="设备名称:" prop="deviceName">
                <el-input v-model="addForm.deviceName" placeholder="请输入设备名"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="设备型号:" prop="model">
                <el-input v-model="addForm.model" placeholder="请输入设备型号"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="设备规格:" prop="specification">
                <el-input v-model="addForm.specification" placeholder="请输入设备规格"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="绑定变量:" prop="attributeId">
                <el-input v-model="addForm.attributeId" placeholder="请输入变量id"></el-input>
               <!-- <el-select v-model="addForm.attributeId" placeholder="请选择设备变量">
                  <el-option
                    v-for="item in deviceBindOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>-->
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-row>
    </el-dialog>
  </el-row>
</template>

<script>
  import BaseEchartsComponent from "../../../components/BaseEcharts/index";
  import myEchartsOptions from '../../../chart-options/echartsOptions'
    export default {
        name: "index",
      components: {BaseEchartsComponent},
      data(){
          return {
            pageStatus: 1,   // 1,新增状态  2，编辑状态
            isViewShow: false,
            isViewEdit: false,
            options: [{value: 2, label: '全部'}, {value: 1, label: '运行'}, {value: 0, label: '关闭'}],
            selectValue: 2,
            selectConditionValue: '',
            tableDatas: [],
            paginationCount: 0,
            currentPage:1,
            pageSize:10,
            addDialogShow: false,
            runLogDialogShow: false,
            pickerType: 'date',
            dateFormat: "yyyy-MM-dd",
            currentDate: new Date(),
            lineChartsOptions: this.validateGlobal.cloneObject(myEchartsOptions.lineChartsOption),
            addForm:{
              deviceName: '',
              model: '',
              specification: '',
              attributeId: ''
            },
            addRule:{
              deviceName: [ { required: true, message: '请输入', trigger: 'blur' }],
              model: [ { required: true, message: '请输入', trigger: 'blur' }],
              specification: [ { required: true, message: '请输入', trigger: 'blur' }],
              attributeId: [ { required: true, message: '请选择', trigger: 'blur' }],
            },
            deviceBindValue: "",
            deviceBindOptions: [{value: "1", label: '设备变量1'}],
            deviceBaseList:[],
            selectItem: '',
            chartTime: ''
          }
      },
      created() {
        this.$emit('fixHeadIndex', "2")
      },
      mounted(){
        let obj = this.validateGlobal.getPermission(2)
        this.isViewShow = obj.isViewShow
        this.isViewEdit = obj.isViewEdit
        this.lineChartsOptions.xAxis[0].data = ["1"]
        this.lineChartsOptions.series[0].data = [0]
        this.lineChartsOptions.xAxis[0].axisLine.lineStyle.color = '#000'
        this.lineChartsOptions.yAxis[0].axisLine.lineStyle.color = '#000'
        this.lineChartsOptions.grid.left = 60
        this.lineChartsOptions.grid.right = 60
        this.lineChartsOptions.series[0].areaStyle.normal.color = '#fff'
        this.lineChartsOptions.title.text = '单位'
        this.askMyDeviceList()
      },
      methods:{
        resetForm: function(){   // 表单重置
           /* if (this.$refs['addForm']!==undefined) {
              this.$refs['addForm'].resetFields();
            }*/

          this.addForm = {
              deviceName: '',
              model: '',
              specification: '',
              attributeId: '',
          }
        },
        onPageChange: function (currentPage) {
          this.currentPage = currentPage;
          this.askMyDeviceList()
        },
        onPickerChange: function (date) {
          this.currentDate = date
          this.askRunLog()
        },
        handlerDelete: function(index, item){
          let _that = this
          let url = _that.ports.deviceManage.delete
          let askData = {
            id: item.id,
          }
          this.http.postForm(url,askData, res => {
            console.log("myDeviceList",res)
            if(!_that.validateGlobal.isEmpty(res) && res.code == 200){
              _that.askMyDeviceList()
              _that.$message('删除成功!');
            }else{
              _that.$message('删除失败!');
            }
          })
        },
        handlerNewDevice: function(){
          if (this.addDialogShow) {
            this.addDialogShow = false
          }else{
            this.addDialogShow = true
          }
          this.pageStatus = 1
          this.resetForm()
          // this.askBaseDeviceList()
        },
        handlerOpenDialog: function (index, item) {
          if (this.runLogDialogShow) {
            this.runLogDialogShow = false
          }else{
            this.runLogDialogShow = true
          }
          this.selectItem = item
          this.askRunLog()
        },
        handlerOpenEditDialog: function(index,item) {
          if (this.addDialogShow) {
            this.addDialogShow = false
          }else{
            this.addDialogShow = true
          }
          this.pageStatus = 2
          this.selectItem = item
          this.addForm = {
            deviceName: this.selectItem.deviceName,
            model: this.selectItem.model,
            specification: this.selectItem.specification,
            attributeId: this.selectItem.attributeId,
          }
        },
        onSelectChange: function(value){
          if (value === 2) {
            this.askMyDeviceList()
          }else{
            this.askMyDeviceList(value)
          }
        },
        onSearch: function(){
          this.askMyDeviceList("",this.selectConditionValue)
        },
        askBaseDeviceList: function() {
          let _that = this
          let gateway = sessionStorage.getItem("gateway")
          let userId = sessionStorage.getItem("userId")
          let url = _that.ports.deviceManage.baseList
          let askData = {
            userId: userId,
            sn: gateway
          }
          this.http.get(url,askData, res => {
            console.log("baseDeviceList",res)
            if(!_that.validateGlobal.isEmpty(res) && res.code == 200){
              if (res.data && res.data.length > 0){
                _that.deviceBaseList = res.data
                let arry = []
                for(let i = 0;i<res.data.length;++i){
                  arry.push({label:res.data[i].deviceName,value: res.data[i].id})
                }
                _that.deviceBindOptions = arry
                _that.addForm.attributeId = arry[0].value
              }
            }else{
              _that.$message('列表获取失败!');
            }
          })
        },
        postNewDevice: function(formName) {
          let _that = this
          this.$refs[formName].validate((valid) => {
            if (!valid){
              _that.$message('输入有误!');
              return false;
            } else{
              let gateway = sessionStorage.getItem("gateway")
              let url = _that.ports.deviceManage.add
              let askData = _that.addForm
              if (_that.pageStatus == 1) {
                askData.sn = gateway
              }else{
                askData.sn = gateway
                askData.id = _that.selectItem.id
              }
              this.http.postForm(url,askData, res => {
                console.log("baseDeviceList",res)
                if(!_that.validateGlobal.isEmpty(res) && res.code == 200){
                   _that.$message("添加成功!")
                   _that.addDialogShow = false
                   _that.askMyDeviceList()
                }else{
                  _that.$message('添加失败!');
                }

              })
            }
          });
        },
        askMyDeviceList: function(operateStatus,searchValue) {
          let _that = this
          let gateway = sessionStorage.getItem("gateway")
          let url = _that.ports.deviceManage.list
          let askData = {
            sn: gateway,
            operateStatus: operateStatus,
            searchValue: searchValue,
            current: _that.currentPage,
            size: _that.pageSize,
          }
          this.http.get(url,askData, res => {
            console.log("myDeviceList",res)
            if(!_that.validateGlobal.isEmpty(res) && res.code == 200){
              if (res.data.records){
                 _that.paginationCount = res.data.total
                 _that.tableDatas = res.data.records
              }
            }else{
              _that.$message('列表获取失败!');
            }
          })
        },
        askRunLog: function() {
          let _that = this
          let url = _that.ports.deviceManage.runLog
          let askData = {
            id: _that.selectItem.id,
            time: _that.currentDate,
          }
          this.http.get(url,askData, res => {
            console.log("runLogList",res)
            if(!_that.validateGlobal.isEmpty(res) && res.code == 200){
              if (res.data){
                let [arryX,arryY] = [[],[]]
                for(let i = 0;i<res.data.length;++i){
                  arryX.push(res.data[i].time)
                  arryY.push(res.data[i].value)
                }
                _that.lineChartsOptions.xAxis[0].data = arryX
                _that.lineChartsOptions.series[0].data = arryY
                _that.$nextTick(()=>{
                  _that.$refs.dmcRunLogLineChart.drawLineGraph('dmc_runloglinechart',_that.lineChartsOptions)
                  _that.chartTime = new Date()
                })
              }
            }else{
              _that.$message('数据获取失败!');
            }
          })
        }
      }

    }
</script>

<style lang="scss">
  #device-manage-container{

    > .el-card{
      margin: 20px 20px 0 20px;
      height: 820px;

      .el-select .el-input {
        width: 130px;
      }

      .input-with-select .el-input-group__prepend {
        background-color: #fff;
      }

      .box-card-content{
        >:nth-child(2).el-row{
          margin-top: 10px;
        }
      }
    }

    .add-dialog-content{
      .el-input{
        width: 160px;
      }
    }

    #dmc_runloglinechart{
      height: 300px;
      width: 100%;
    }
  }

</style>
